﻿using System;
using System.Xml;
using System.Linq;
using System.Collections.Generic;
using Infrastructure.Serialization;

namespace PasswordControl.Core.Data
{
    public class PasswordItem : IPasswordItem, ISerializable
    {
        private ICollection<IIdentificationItem> m_identificationFields = new List<IIdentificationItem>();

        [StoredValue]
        public string ItemName { get; set; }

        [StoredValue]
        public string Username { get; set; }

        [StoredValue]
        public string Password { get; set; }

        [StoredValue]
        public string Group { get; set; }

        public IEnumerable<IIdentificationItem> IdentificationFields
        {
            get { return m_identificationFields; }
        }

        public PasswordItem()
        {
        }

        public PasswordItem(string itemName)
        {
            ItemName = itemName;
        }

        public void SetIdentificationField(string name, string value)
        {
            var field = m_identificationFields.SingleOrDefault(f => f.ItemName == name);
            if (field != null) field.ItemValue = value;
            else m_identificationFields.Add(new IdentificationItem(name, value));
        }

        public void RemoveIdentificationField(string name)
        {
            var field = m_identificationFields.SingleOrDefault(f => f.ItemName == name);
            if (field == null) return;
            m_identificationFields.Remove(field);
        }

        #region ISerializable

        public void OnSerialize(ISerializer serializer, XmlNode node)
        {
            serializer.SerializeCollection(node, m_identificationFields);
        }

        public void OnDeserialize(ISerializer serializer, XmlNode node)
        {
            serializer.DeserializeNodesOfType<IdentificationItem>(node)
                .ToList().ForEach(item => m_identificationFields.Add(item));
        }

        #endregion
    }
}
